import java.io.{File, FileInputStream}
import java.text.SimpleDateFormat

import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.StringUtils

import scala.collection.JavaConverters._
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.Source
import org.apache.poi.ss.usermodel.{Cell, CellType, DateUtil, Row}
import org.apache.poi.xssf.usermodel.XSSFWorkbook

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

/**
  * Created by yz on 2019/1/23
  */
object Utils {

  def txt2Lines(file: File) = {
    FileUtils.readLines(file).asScala
  }

  def splitByTab(str:String)=str.split("\t").toBuffer

  def txt2LinesByScala(file: File) = {
    val source = Source.fromFile(file)
    try source.getLines().toBuffer finally source.close()
  }

  def lines2columns(lines: mutable.Buffer[String]) = {
    lines.map(x => x.split("\t").toBuffer)
  }

  def logTime(startTime: Long) = {
    val time = getTime(startTime)
    println(time)
  }

  def getTime(startTime: Long) = {
    val endTime = System.currentTimeMillis()
    (endTime - startTime) / 1000.0
  }

  def lines2File(file: File, lines: mutable.Buffer[String], append: Boolean = false) = {
    FileUtils.writeLines(file, lines.asJava, append)
  }

  def execFuture[T](f: Future[T]): T = {
    Await.result(f, Duration.Inf)
  }



  def xlsx2Lines(xlsxFile: File, sheetIndex: Int): ArrayBuffer[String] = {
    val is = new FileInputStream(xlsxFile.getAbsolutePath)
    val xssfWorkbook = new XSSFWorkbook(is)
    val xssfSheet = xssfWorkbook.getSheetAt(sheetIndex)
    val lines = ArrayBuffer[String]()
    for (i <- 0 to xssfSheet.getLastRowNum) {
      val xssfRow = xssfSheet.getRow(i)
      val columns = ArrayBuffer[String]()
      for (j <- 0 until xssfRow.getLastCellNum) {
        val cell = xssfRow.getCell(j)
        var value = ""
        if (cell != null) {
          cell.getCellType match {
            case Cell.CELL_TYPE_STRING =>
              value = cell.getStringCellValue
            case Cell.CELL_TYPE_NUMERIC =>
              if (DateUtil.isCellDateFormatted(cell)) {
                val dateFormat = new SimpleDateFormat("yyyy/MM/dd")
                value = dateFormat.format(cell.getDateCellValue)
              } else {
                val doubleValue = cell.getNumericCellValue
                value = if (doubleValue == doubleValue.toInt) {
                  doubleValue.toInt.toString
                } else doubleValue.toString
              }
            case Cell.CELL_TYPE_BLANK =>
              value = ""
            case _ =>
              value = ""
          }
        }

        columns += value.replaceAll("\n", " ")
      }
      val line = columns.mkString("\t")
      lines += line
    }
    xssfWorkbook.close()
    lines.filter(StringUtils.isNotBlank(_))
  }



}
